let io = require('socket.io')(8080)
let fs = require('fs')
let db = require('./db')
let cache = require('./cache')

io.on('connection', function(socket) {
  let query = socket.handshake.query
  if(!query.to || !query.uid) {
    socket.disconnect();
    return
  }

  // 验证用户
  db.login(query).then((user) => {
    socket.on('message', async message => {
      try{
        var room = cache.room(query.uid, query.to)
        let result = await db.store({ ...query, content: message.content, room })
        socket.broadcast.to(room).emit('message', message)
      }catch(err) {
        console.log(err)
      }
    })
    cache.join(query.uid, query.to, socket)
    socket.on('disconnect', reason => {
      cache.leave(query.uid, query.to)
    })
    // 获取最近聊天记录
    return db.getChat({ uid: query.to, to: query.uid})
  }).then((record) => {
    // 返回聊天记录数据
    socket.emit('chat', record)
  }).catch((err) => {
    console.log(err)
    socket.disconnect()
  })
})

// 发送最近聊天记录 chat
// socket.emit('chat', {})


// 发送用户记录  record